[[...path]].page.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  21. import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsLatestRevision,
  30. useIsForbidden, useIsNotFound, useIsSharedUser,
  31. useIsEnabledStaleNotification, useIsIdenticalPath,
  32. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  33. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  34. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  35. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  36. useIsSlackConfigured, useRendererConfig,
  37. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  38. } from '~/stores/context';
  39. import { useEditingMarkdown } from '~/stores/editor';
  40. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  41. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  42. import { useRedirectFrom } from '~/stores/page-redirect';
  43. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  44. import { useSelectedGrant } from '~/stores/ui';
  45. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  46. import loggerFactory from '~/utils/logger';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  49. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  61. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  62. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  63. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  64. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  65. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  66. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  67. const logger = loggerFactory('growi:pages:all');
  68. const {
  69. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  70. } = pagePathUtils;
  71. const { removeHeadingSlash } = pathUtils;
  72. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  73. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  74. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  75. {
  76. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  77. return v?.data != null
  78. && v?.data.toObject != null
  79. && v?.meta != null
  80. && isIPageInfoForEntity(v.meta);
  81. },
  82. serialize: (v) => {
  83. return {
  84. data: superjson.stringify(v.data.toObject()),
  85. meta: superjson.stringify(v.meta),
  86. };
  87. },
  88. deserialize: (v) => {
  89. return {
  90. data: superjson.parse(v.data),
  91. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  92. };
  93. },
  94. },
  95. 'IPageToShowRevisionWithMetaTransformer',
  96. );
  97. // GrowiContextualSubNavigation for NOT shared page
  98. type GrowiContextualSubNavigationProps = {
  99. isLinkSharingDisabled: boolean,
  100. }
  101. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  102. const { isLinkSharingDisabled } = props;
  103. const { data: currentPage } = useSWRxCurrentPage();
  104. return (
  105. <div data-testid="grw-contextual-sub-nav">
  106. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  107. </div>
  108. );
  109. };
  110. const PutbackPageModal = (): JSX.Element => {
  111. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  112. return <PutbackPageModal />;
  113. };
  114. type Props = CommonProps & {
  115. pageWithMeta: IPageToShowRevisionWithMeta | null,
  116. // pageUser?: any,
  117. redirectFrom?: string;
  118. // shareLinkId?: string;
  119. isLatestRevision?: boolean,
  120. isIdenticalPathPage?: boolean,
  121. isForbidden: boolean,
  122. isNotFound: boolean,
  123. isNotCreatable: boolean,
  124. // isAbleToDeleteCompletely: boolean,
  125. templateTagData?: string[],
  126. templateBodyData?: string,
  127. isSearchServiceConfigured: boolean,
  128. isSearchServiceReachable: boolean,
  129. isSearchScopeChildrenAsDefault: boolean,
  130. isSlackConfigured: boolean,
  131. // isMailerSetup: boolean,
  132. isAclEnabled: boolean,
  133. // hasSlackConfig: boolean,
  134. drawioUri: string | null,
  135. hackmdUri: string,
  136. noCdn: string,
  137. // highlightJsStyle: string,
  138. isAllReplyShown: boolean,
  139. isContainerFluid: boolean,
  140. editorConfig: EditorConfig,
  141. isEnabledStaleNotification: boolean,
  142. isEnabledAttachTitleHeader: boolean,
  143. // isEnabledLinebreaks: boolean,
  144. // isEnabledLinebreaksInComments: boolean,
  145. adminPreferredIndentSize: number,
  146. isIndentSizeForced: boolean,
  147. disableLinkSharing: boolean,
  148. grantData?: IPageGrantData,
  149. rendererConfig: RendererConfig,
  150. };
  151. const Page: NextPageWithLayout<Props> = (props: Props) => {
  152. // register global EventEmitter
  153. if (isClient() && window.globalEmitter == null) {
  154. window.globalEmitter = new EventEmitter();
  155. }
  156. const router = useRouter();
  157. useCurrentUser(props.currentUser ?? null);
  158. // commons
  159. useEditorConfig(props.editorConfig);
  160. useCsrfToken(props.csrfToken);
  161. // page
  162. useIsLatestRevision(props.isLatestRevision);
  163. useIsContainerFluid(props.isContainerFluid);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotFound(props.isNotFound);
  167. useIsNotCreatable(props.isNotCreatable);
  168. useRedirectFrom(props.redirectFrom ?? null);
  169. useIsSharedUser(false); // this page cann't be routed for '/share'
  170. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  171. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  172. useIsSearchPage(false);
  173. useTemplateTagData(props.templateTagData);
  174. useTemplateBodyData(props.templateBodyData);
  175. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. useDrawioUri(props.drawioUri);
  184. useHackmdUri(props.hackmdUri);
  185. // useNoCdn(props.noCdn);
  186. useDefaultIndentSize(props.adminPreferredIndentSize);
  187. useIsIndentSizeForced(props.isIndentSizeForced);
  188. useDisableLinkSharing(props.disableLinkSharing);
  189. useRendererConfig(props.rendererConfig);
  190. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  191. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  192. useIsAllReplyShown(props.isAllReplyShown);
  193. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  194. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  195. const { pageWithMeta } = props;
  196. const pageId = pageWithMeta?.data._id;
  197. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  198. const revisionBody = pageWithMeta?.data.revision?.body;
  199. useCurrentPageId(pageId ?? null);
  200. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  201. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  202. useCurrentPathname(props.currentPathname);
  203. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  204. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  205. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  206. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  207. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  208. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  209. useSetupGlobalSocket();
  210. useSetupGlobalSocketForPage(pageId);
  211. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  212. const shouldRenderPutbackPageModal = pageWithMeta != null
  213. ? _isTrashPage(pageWithMeta.data.path)
  214. : false;
  215. // sync grant data
  216. useEffect(() => {
  217. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  218. mutateSelectedGrant(grantDataToApply);
  219. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  220. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  221. useEffect(() => {
  222. const decodedURI = decodeURI(window.location.pathname);
  223. if (isClient() && decodedURI !== props.currentPathname) {
  224. const { search, hash } = window.location;
  225. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  226. }
  227. }, [props.currentPathname, router]);
  228. // initialize mutateEditingMarkdown only once per page
  229. // need to include useCurrentPathname not useCurrentPagePath
  230. useEffect(() => {
  231. if (props.currentPathname != null) {
  232. mutateEditingMarkdown(revisionBody);
  233. }
  234. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  235. useEffect(() => {
  236. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  237. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  238. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  239. const title = generateCustomTitleForPage(props, pagePath);
  240. return (
  241. <>
  242. <Head>
  243. <title>{title}</title>
  244. </Head>
  245. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  246. <header className="py-0 position-relative">
  247. <div id="grw-subnav-container">
  248. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  249. </div>
  250. </header>
  251. <div className="d-edit-none">
  252. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  253. </div>
  254. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  255. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  256. <DisplaySwitcher
  257. pageView={
  258. <PageView
  259. pagePath={pagePath}
  260. initialPage={pageWithMeta?.data}
  261. rendererConfig={props.rendererConfig}
  262. />
  263. }
  264. />
  265. <PageStatusAlert />
  266. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  267. </div>
  268. </>
  269. );
  270. };
  271. type LayoutProps = Props & {
  272. children?: ReactNode
  273. }
  274. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  275. const className = useEditorModeClassName();
  276. // init sidebar config with UserUISettings and sidebarConfig
  277. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  278. return (
  279. <BasicLayout className={className}>
  280. {children}
  281. </BasicLayout>
  282. );
  283. };
  284. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  285. return (
  286. <>
  287. <DrawioViewerScript />
  288. <Layout {...page.props}>
  289. {page}
  290. </Layout>
  291. <UnsavedAlertDialog />
  292. <DescendantsPageListModal />
  293. <DrawioModal />
  294. <HandsontableModal />
  295. </>
  296. );
  297. };
  298. function getPageIdFromPathname(currentPathname: string): string | null {
  299. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  300. }
  301. class MultiplePagesHitsError extends ExtensibleCustomError {
  302. pagePath: string;
  303. constructor(pagePath: string) {
  304. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  305. this.pagePath = pagePath;
  306. }
  307. }
  308. // apply parent page grant fot creating page
  309. async function applyGrantToPage(props: Props, ancestor: any) {
  310. await ancestor.populate('grantedGroup');
  311. const grant = {
  312. grant: ancestor.grant,
  313. };
  314. const grantedGroup = ancestor.grantedGroup ? {
  315. grantedGroup: {
  316. id: ancestor.grantedGroup.id,
  317. name: ancestor.grantedGroup.name,
  318. },
  319. } : {};
  320. props.grantData = Object.assign(grant, grantedGroup);
  321. }
  322. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  323. const { model: mongooseModel } = await import('mongoose');
  324. const req: CrowiRequest = context.req as CrowiRequest;
  325. const { crowi } = req;
  326. const { revisionId } = req.query;
  327. const Page = crowi.model('Page') as PageModel;
  328. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  329. const { pageService } = crowi;
  330. let currentPathname = props.currentPathname;
  331. const pageId = getPageIdFromPathname(currentPathname);
  332. const isPermalink = _isPermalink(currentPathname);
  333. const { user } = req;
  334. if (!isPermalink) {
  335. // check redirects
  336. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  337. if (chains != null) {
  338. // overwrite currentPathname
  339. currentPathname = chains.end.toPath;
  340. props.currentPathname = currentPathname;
  341. // set redirectFrom
  342. props.redirectFrom = chains.start.fromPath;
  343. }
  344. // check whether the specified page path hits to multiple pages
  345. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  346. if (count > 1) {
  347. throw new MultiplePagesHitsError(currentPathname);
  348. }
  349. }
  350. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  351. const page = pageWithMeta?.data as unknown as PageDocument;
  352. // add user to seen users
  353. if (page != null && user != null) {
  354. await page.seen(user);
  355. }
  356. // populate & check if the revision is latest
  357. if (page != null) {
  358. page.initLatestRevisionField(revisionId);
  359. await page.populateDataToShowRevision();
  360. props.isLatestRevision = page.isLatestRevision();
  361. }
  362. if (page == null && user != null) {
  363. const templateData = await Page.findTemplate(props.currentPathname);
  364. if (templateData != null) {
  365. props.templateTagData = templateData.templateTags as string[];
  366. props.templateBodyData = templateData.templateBody as string;
  367. }
  368. // apply pagrent page grant
  369. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  370. if (ancestor != null) {
  371. await applyGrantToPage(props, ancestor);
  372. }
  373. }
  374. props.pageWithMeta = pageWithMeta;
  375. }
  376. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  377. const req: CrowiRequest = context.req as CrowiRequest;
  378. const { crowi } = req;
  379. const Page = crowi.model('Page') as PageModel;
  380. const { currentPathname } = props;
  381. const pageId = getPageIdFromPathname(currentPathname);
  382. const isPermalink = _isPermalink(currentPathname);
  383. const page = props.pageWithMeta?.data;
  384. if (props.isIdenticalPathPage) {
  385. props.isNotCreatable = true;
  386. }
  387. else if (page == null) {
  388. props.isNotFound = true;
  389. props.isNotCreatable = !isCreatablePage(currentPathname);
  390. // check the page is forbidden or just does not exist.
  391. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  392. props.isForbidden = count > 0;
  393. }
  394. else {
  395. props.isNotFound = page.isEmpty;
  396. props.isNotCreatable = false;
  397. props.isForbidden = false;
  398. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  399. if (isPermalink && page.isEmpty) {
  400. props.currentPathname = page.path;
  401. }
  402. // /path/to/page ==> /62a88db47fed8b2d94f30000
  403. if (!isPermalink && !page.isEmpty) {
  404. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  405. if (!isToppage) {
  406. props.currentPathname = `/${page._id}`;
  407. }
  408. }
  409. }
  410. }
  411. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  412. // const req: CrowiRequest = context.req as CrowiRequest;
  413. // const { crowi } = req;
  414. // const UserModel = crowi.model('User');
  415. // if (isUserPage(props.currentPagePath)) {
  416. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  417. // if (user != null) {
  418. // props.pageUser = JSON.stringify(user.toObject());
  419. // }
  420. // }
  421. // }
  422. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  423. const req: CrowiRequest = context.req as CrowiRequest;
  424. const { crowi } = req;
  425. const {
  426. searchService, configManager, aclService,
  427. } = crowi;
  428. props.isSearchServiceConfigured = searchService.isConfigured;
  429. props.isSearchServiceReachable = searchService.isReachable;
  430. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  431. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  432. // props.isMailerSetup = mailService.isMailerSetup;
  433. props.isAclEnabled = aclService.isAclEnabled();
  434. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  435. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  436. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  437. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  438. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  439. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  440. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  441. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  442. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  443. props.editorConfig = {
  444. upload: {
  445. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  446. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  447. },
  448. };
  449. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  450. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  451. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  452. props.rendererConfig = {
  453. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  454. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  455. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  456. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  457. plantumlUri: process.env.PLANTUML_URI ?? null,
  458. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  459. // XSS Options
  460. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  461. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  462. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  463. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  464. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  465. };
  466. }
  467. /**
  468. * for Server Side Translations
  469. * @param context
  470. * @param props
  471. * @param namespacesRequired
  472. */
  473. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  474. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  475. props._nextI18Next = nextI18NextConfig._nextI18Next;
  476. }
  477. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  478. const req = context.req as CrowiRequest<IUserHasId & any>;
  479. const { user } = req;
  480. const result = await getServerSideCommonProps(context);
  481. // check for presence
  482. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  483. if (!('props' in result)) {
  484. throw new Error('invalid getSSP result');
  485. }
  486. const props: Props = result.props as Props;
  487. if (props.redirectDestination != null) {
  488. return {
  489. redirect: {
  490. permanent: false,
  491. destination: props.redirectDestination,
  492. },
  493. };
  494. }
  495. if (user != null) {
  496. props.currentUser = user.toObject();
  497. }
  498. try {
  499. await injectPageData(context, props);
  500. }
  501. catch (err) {
  502. if (err instanceof MultiplePagesHitsError) {
  503. props.isIdenticalPathPage = true;
  504. }
  505. else {
  506. throw err;
  507. }
  508. }
  509. await injectRoutingInformation(context, props);
  510. injectServerConfigurations(context, props);
  511. await injectNextI18NextConfigurations(context, props, ['translation']);
  512. return {
  513. props,
  514. };
  515. };
  516. export default Page;